<script setup>
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'
import { Download } from '@element-plus/icons-vue'
import { saveAs } from 'file-saver'
import { getTurnoverStatistics, getUserStatistics, getOrdersStatistics, getTop10Statistics ,exportInfor } from '@/api/index.js'

const orderChart = ref(null)
const chart = ref(null)
const userChart = ref(null)
const sancksChart = ref(null)

const timeRange = ref([]) //时间
const beginTime = ref('') //开始时间
const endTime = ref('') //结束时间

const dateList = ref([]) //X时间
const turnoverList = ref([]) //Y营业额

const dateOrderList = ref([]) //订单统计时间
const orderCompletionRate = ref() //订单完成率
const orderCountList = ref() //每日订单数
const totalOrderCount = ref() //订单总数
const validOrderCount = ref() //有效订单数
const validOrderCountList = ref() //每日有效订单数

const nameList = ref() //商品名称列表
const numberList = ref() //销量列表

const dateUserList = ref([]) //统计用户时间
const totalUserList = ref([]) //用户总量
const newUserList = ref([]) //新增用户

// 获取今天日期
const today = new Date()
const todayStr = today.toISOString().split('T')[0] // 格式化为 'YYYY-MM-DD'

// 初始化 beginTime 和 endTime 的初始值为今天的时间
beginTime.value = todayStr
endTime.value = todayStr

//最近时间
const shortcuts = [
  {
    text: '最近7天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 时间转换为特定格式（例如 "yyyy-MM-dd ")
const formatDateTime = date => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 选择时间时
const handleSubmit = () => {
  if (timeRange.value.length === 2) {
    beginTime.value = formatDateTime(new Date(timeRange.value[0]))
    endTime.value = formatDateTime(new Date(timeRange.value[1]))
  }
  getTurnoverStatisticsList()
  getOrderStatisticsList()
  getSnacksStatisticsList()
  getUserStatisticsList()
}

onMounted(() => {
  initOrderChart()
  initChart()
  initUserChart()
  initSnacksChart()
  getTurnoverStatisticsList()
  getUserStatisticsList()
  getOrderStatisticsList()
  getSnacksStatisticsList()
})

//订单图表
const initOrderChart = () => {
  const myOrderChart = echarts.init(orderChart.value)
  const option = {
    title: {
      text: '订单统计'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['每日订单数', '有效订单'],
      orient: 'horizontal',
      bottom: 10 // 距离底部的距离
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dateOrderList.value
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '每日订单数',
        type: 'line',
        stack: 'Total',
        data: orderCountList.value
      },
      {
        name: '有效订单',
        type: 'line',
        stack: 'Total',
        data: validOrderCountList.value
      }
    ]
  }
  myOrderChart.setOption(option)
}

//营业额图表
const initChart = () => {
  const myChart = echarts.init(chart.value)
  const option = {
    title: {
      text: '营业额统计'
    },
    tooltip: {
      trigger: 'axis'
    },

    xAxis: {
      type: 'category',
      data: dateList.value
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: turnoverList.value,
        type: 'line'
      }
    ]
  }
  myChart.setOption(option)
}

//用户图表
const initUserChart = () => {
  const myUserChart = echarts.init(userChart.value)

  const option = {
    title: {
      text: '用户统计'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['用户总量', '新增用户'],
      orient: 'horizontal',
      bottom: 10 // 距离底部的距离
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dateUserList.value
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '用户总量',
        type: 'line',
        stack: 'Total',
        data: totalUserList.value
      },
      {
        name: '新增用户',
        type: 'line',
        stack: 'Total',
        data: newUserList.value
      }
    ]
  }
  myUserChart.setOption(option)
}

//零食top10图表
const initSnacksChart = () => {
  const mySnacksChart = echarts.init(sancksChart.value)
  const option = {
    title: {
      text: '零食销量统计'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: [
      {
        type: 'category',
        data: nameList.value,
        axisTick: {
          alignWithLabel: true
        }
      }
    ],
    yAxis: [
      {
        type: 'value'
      }
    ],
    series: [
      {
        name: 'Direct',
        type: 'bar',
        barWidth: '60%',
        data: numberList.value
      }
    ]
  }
  mySnacksChart.setOption(option)
}

//获取营业额数据
const getTurnoverStatisticsList = async () => {
  const res = await getTurnoverStatistics(beginTime.value, endTime.value)
  console.log("营业额",res.data)
  if (res.data.code === 1) {
    const data = res.data.data
    // 解析后端返回的数据
    dateList.value = data.dateList.split(',')
    turnoverList.value = data.turnoverList.split(',').map(Number) // 将字符串转换为数字数组
  }
  initChart() // 更新完数据后再初始化图表
}

//获取订单数据
const getOrderStatisticsList = async () => {
  const res = await getOrdersStatistics(beginTime.value, endTime.value)
  console.log('订单', res.data)
  if (res.data.code === 1) {
    const data = res.data.data
    dateOrderList.value = data.dateList.split(',')
    orderCountList.value = data.orderCountList.split(',').map(Number) // 将字符串转换为数字数组
    totalOrderCount.value = data.totalOrderCount
    validOrderCount.value = data.validOrderCount
    validOrderCountList.value = data.validOrderCountList.split(',').map(Number) // 将字符串转换为数字数组
    orderCompletionRate.value = data.orderCompletionRate
  }
  initOrderChart()
}

//获取零食top10数据
const getSnacksStatisticsList = async () => {
  const res = await getTop10Statistics(beginTime.value, endTime.value)
  console.log('零食', res.data)
  if (res.data.code === 1) {
    const data = res.data.data
    nameList.value = data.nameList.split(',')
    numberList.value = data.numberList.split(',').map(Number) // 将字符串转换为数字数组
  }
  initSnacksChart()
}

//获取用户数据
const getUserStatisticsList = async () => {
  const res = await getUserStatistics(beginTime.value, endTime.value)
  console.log("用户",res.data)
  if (res.data.code === 1) {
    const data = res.data.data
    // 解析后端返回的数据
    dateUserList.value = data.dateList.split(',')
    totalUserList.value = data.totalUserList.split(',').map(Number) // 将字符串转换为数字数组
    newUserList.value = data.newUserList.split(',').map(Number) // 将字符串转换为数字数组
    initUserChart() // 更新完数据后再初始化图表
  }
}


const handleExport = async () => {
      try {
        const { data } = await exportInfor();
        let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }));
        var a = document.createElement('a');
        document.body.appendChild(a);
        a.href = url;
        a.download = '运营数据统计报表.xlsx';
        a.click();
        window.URL.revokeObjectURL(url);
      } catch (error) {
        console.error('下载文件时出现错误:', error);
        ElMessage.error('导出失败，请重试');
      }
    };
</script>
<template>
  <div class="statisticsTime">
    <div><label class="stTime">统计营业额区间时间：</label>
    <el-date-picker v-model="timeRange" type="datetimerange" :shortcuts="shortcuts" range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间" format="YYYY-MM-DD" date-format="YYYY-MM-DD" @change="handleSubmit" /></div>
    
  <div>  <el-button type="primary"  @click="handleExport" round > 导出数据<el-icon size="30"><Download /></el-icon></el-button> </div>
   
  </div>

  <div class="chart-container">
    <div class="chart-wrapper">
      <div ref="chart" class="chart" style="width: 600px; height: 400px;"></div>
      <p class="chart-description">营业额（元）</p>
    </div>
    <div class="chart-wrapper">
      <p> <span>订单完成率{{ (orderCompletionRate  * 100).toFixed(2) }}% </span><span>有效订单{{ validOrderCount }}</span><span>订单总数{{ totalOrderCount }} </span></p>
      <div ref="orderChart" class="chart" style="width: 600px; height: 400px;"></div>
    </div>
  </div>

  <div class="chart-container">

    <div class="chart-wrapper">
      <div ref="userChart" class="chart" style="width: 600px; height: 400px;"></div>
    </div>
    <div class="chart-wrapper">
      <div ref="sancksChart" class="chart" style="width: 600px; height: 400px;"></div>
      <p class="chart-description">销量TOP10</p>
    </div>
  </div>

</template>


<style lang="scss" scoped>
.statisticsTime {
 display: flex;
 justify-content: space-between ;
  margin-bottom: 20px;
  .stTime {
   
    font-size: 18px;
  }
}

.chart-container {
  display: flex;
  justify-content: space-around; // 在容器中间排列两个图表
}

.chart-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 20px;
  background-color: #fff;
  p span {
    margin-right: 20px; /* 设置右侧间距为 20px，可以根据需要调整间距大小 */
  }
}

.chart {
  margin-right: 5px;
}

.chart-description {
  margin-top: 10px;
  font-size: 18px;
}
</style>